# 2.11 练习题- ⽤户登录认证程序
# 要求⽤户输⼊帐号密码进⾏登陆
# ⽤户账号信息保存在⽂件内
# ⽤户密码输⼊错误三次后锁定⽤户，下次再登录，检测到是这个被锁定的⽤户，则依然不允许其它
# 登录，提示已被锁

import json, os

def login_cou(text):    # 输入账号
    keys = json.loads(text)
    # print(keys)
    while True:
        count = input('请输入账号：')
        if count in keys:
            return login_pwd(count, keys)
        print('账号不存在！')

def login_pwd(count, keys): # 输入密码
    n = 3
    while n:
        passwd = input('请输入密码：')
        if keys[count][1]=="1":
            break
        if passwd==keys[count][0]:
            print('登陆成功！')
            return keys
        print('密码错误，你还有{}次机会！'.format(n-1))
        n -= 1
    print('该账户已锁定！')
    keys[count][1]="1"
    return keys
    
if __name__ == '__main__':
    # with open('keys.json', 'w', encoding='utf-8') as fp:    # 创建测试账户
    #     fp.write('{"admin":["admin","0"]}')
    with open('keys.json', 'r', encoding='utf-8') as fp:
        text = fp.read()
        dics = login_cou(text)
        jsonStr = json.dumps(dics)
        # print(jsonStr)
        with open('newkeys.json', 'w', encoding='utf-8') as newfp:
            newfp.write(jsonStr)
    os.remove('keys.json')
    os.rename('newkeys.json', 'keys.json')

